<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import ProvincePicker from '@/components/province-picker/index.vue'
import { useGlobalStore } from '@/store/global'

const globalStore = useGlobalStore()

// 表单数据
const formData = reactive({
  region: '',
  detailAddress: '',
  recipientName: '',
  phone: ''
})

// 省市县选择器相关
const showProvincePicker = ref(false)
const selectedRegion = ref({
  province: '',
  city: '',
  district: '',
  fullAddress: ''
})

// 页面参数
const addressId = ref(null)

onLoad((options) => {
  if (options.id) {
    addressId.value = options.id
    // TODO: 根据ID加载地址信息
    loadAddressInfo(options.id)
  }
})

// 加载地址信息（编辑模式）
const loadAddressInfo = async (id) => {
  try {
    // TODO: 调用API获取地址详情
    // const result = await getAddressDetailApi(id)
    // Object.assign(formData, result)
    console.log('加载地址信息:', id)
  } catch (error) {
    console.error('加载地址信息失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'error'
    })
  }
}

// 打开地区选择器
const openRegionPicker = () => {
  showProvincePicker.value = true
}

// 确认地区选择
const handleRegionConfirm = (result) => {
  selectedRegion.value = result
  formData.region = result.fullAddress
  uni.showToast({
    title: '地区选择成功',
    icon: 'success',
    duration: 1000
  })
}

// 取消地区选择
const handleRegionCancel = () => {
  console.log('取消选择地区')
}

// 表单验证
const validateForm = () => {
  const errors = []

  if (!formData.region.trim()) {
    errors.push('请选择收货地区')
  }

  if (!formData.detailAddress.trim()) {
    errors.push('请输入详细地址')
  }

  if (!formData.recipientName.trim()) {
    errors.push('请输入收货人姓名')
  } else if (!/^[\u4e00-\u9fa5]{2,4}$/.test(formData.recipientName)) {
    errors.push('姓名请输入2-4个中文字符')
  }

  if (!formData.phone.trim()) {
    errors.push('请输入手机号')
  } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.push('请输入正确的手机号')
  }

  return errors
}

// 保存地址
const handleSave = async () => {
  const errors = validateForm()

  if (errors.length > 0) {
    uni.showToast({
      title: errors[0],
      icon: 'none',
      duration: 2000
    })
    return
  }

  try {
    uni.showLoading({
      title: '保存中...'
    })

    // TODO: 调用保存API
    if (addressId.value) {
      // 编辑模式
      // await updateAddressApi({
      //   id: addressId.value,
      //   region: formData.region,
      //   detailAddress: formData.detailAddress,
      //   recipientName: formData.recipientName,
      //   phone: formData.phone
      // })
      console.log('更新地址:', formData)
    } else {
      // 新增模式
      // await addAddressApi({
      //   region: formData.region,
      //   detailAddress: formData.detailAddress,
      //   recipientName: formData.recipientName,
      //   phone: formData.phone
      // })
      console.log('新增地址:', formData)
    }

    uni.hideLoading()
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1000
    })

    setTimeout(() => {
      uni.navigateBack()
    }, 1000)

  } catch (error) {
    uni.hideLoading()
    console.error('保存地址失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    })
  }
}
</script>

<template>
    <view class="app-edit">
        <uni-forms class="app-form">
            <view class="form-item">
                <view class="item-title">
                    <text>*</text>
                    <text>收货地址</text>
                </view>
                <view class="item-content region-select" @click="openRegionPicker">
                    <text>收货地区</text>
                    <view class="select-wrapper">
                        <text class="select-text">{{ formData.region || '省市县、乡镇等' }}</text>
                        <uni-icons type="bottom" size="20" color="#3333332e"></uni-icons>
                    </view>
                </view>
                <view class="item-content">
                    <text>详细地址</text>
                    <input 
                        v-model="formData.detailAddress"
                        placeholder="请输入详细地址" 
                    />
                </view>
            </view>

            <view class="form-item">
                <view class="item-title">
                    <text>*</text>
                    <text>其他信息</text>
                </view>
                <view class="item-content">
                    <text>收货人姓名</text>
                    <input 
                        v-model="formData.recipientName"
                        placeholder="请输入收货人姓名" 
                    />
                </view>
                <view class="item-content">
                    <text>手机号</text>
                    <input 
                        v-model="formData.phone"
                        type="number"
                        placeholder="请输入手机号" 
                    />
                </view>
            </view>
        </uni-forms>

        <view class="form-button" @click="handleSave">保存</view>

        <!-- 省市县选择器 -->
        <ProvincePicker 
            v-model="selectedRegion"
            :show="showProvincePicker"
            :province-data="globalStore.provinceData"
            @update:show="showProvincePicker = $event"
            @confirm="handleRegionConfirm"
            @cancel="handleRegionCancel"
        />
    </view>
</template>

<style src="./style.scss" scoped />